﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using nHydrate.GeoLocation.Interfaces;

namespace Widgetsphere.Autos.API
{
    public static class Extensions
    {
        public static bool GeoLocationCodeListContains(this List<GeoLocationCode> source, double latitudeValue, double longitudeValue)
        {
            return source.Any(item => (latitudeValue == item.Latitude) && (longitudeValue == item.Longitude));
        }

        public static GeoLocationCode GetGeoLocationCodeFromList(this List<GeoLocationCode> source, double latitudeValue, double longitudeValue)
        {
            return source.Where(x => x.Latitude == latitudeValue && x.Longitude == longitudeValue).FirstOrDefault();
        }

        public static GeoLocationCode GetGeoLocationCodeCenter(this List<GeoLocationCode> source)
        {
            try
            {
                //Error Check
                if (source.Count == 0)
                {
                    return null;
                }

                var x1 = double.MaxValue;
                var y1 = double.MaxValue;
                var x2 = double.MinValue;
                var y2 = double.MinValue;
                foreach (var geo in source)
                {
                    if (geo.IsValid)
                    {
                        if (x1 > geo.Latitude)
                            x1 = geo.Latitude;
                        if (y1 > geo.Longitude)
                            y1 = geo.Longitude;
                        if (x2 < geo.Latitude)
                            x2 = geo.Latitude;
                        if (y2 < geo.Longitude)
                            y2 = geo.Longitude;
                    }
                }
                return new GeoLocationCode(x1 + (x2 - x1) / 2, y1 + (y2 - y1) / 2);
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
                return null;
            }
        }

        /// <summary>
        /// Add commas to a number
        /// </summary>
        public static string FormatNumber(this int number)
        {
            return number.ToString("###,###,###,##0");
        }

        public static string GetCeleriqDisplayName(this HP.Datastore.Common.DimensionItem dimension, Dictionary<string, string> orderList)
        {
            var headerText = dimension.Name;
            if (orderList.ContainsKey(dimension.Name))
                headerText = orderList[dimension.Name];
            return headerText;
        }

        public static string GetCeleriqDisplayName(string fieldName, Dictionary<string, string> orderList)
        {
            var headerText = fieldName;
            if (orderList.ContainsKey(fieldName))
                headerText = orderList[fieldName];
            return headerText;
        }

    }

}
